package com.example.gulimall.cas.service.impl;

import com.example.gulimall.cas.dao.PermissionDAO;
import com.example.gulimall.common.service.RbacService;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * <p>@description: 权限控制  </p>
 * <p>@author: JGD </p>
 * <p>@create: 2020/3/16 10:03 </p>
 * <p>@version : 2.0.0
 **/
@Service(value = "rbacService")
public class RbacServiceImpl implements RbacService {
    @Resource
    private PermissionDAO permissionDAO;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        String requestUri = request.getRequestURI();
        return hasPermission(requestUri, authentication);
    }

    private boolean hasPermission(String requestUri, Authentication authentication) {
        String name = authentication.getName();
        boolean hasPermission = false;
        Set<String> list = permissionDAO.selectPermissionUrl(name);
        //读取用户所拥有权限的所有URI
        for (String uri : list) {
            if (antPathMatcher.match(uri, requestUri)) {
                hasPermission = true;
                break;
            }
        }
        return hasPermission;
    }

}
